//
//  SearchResultViewController.m
//  suRead
//
//  Created by Kobe LI on 16/4/27.
//  Copyright © 2016年 bao. All rights reserved.
//

#import "SearchResultViewController.h"

#import "ServiceNews.h"
#import "Masonry.h"
#import "MJRefresh.h"
#import "UIViewController+HUD.h"
#import "UIImageView+WebCache.h"

#import "M_News.h"

#import "NewsCell.h"
#import "NewsImageCell.h"
#import "NewsAdvCell.h"

#import "NewsDetailViewController.h"
#import "NewsAlbumViewController.h"
#import "NewsWebViewController.h"
#import "SpecialNewsListViewController.h"


#define ScreenRectHeight [UIScreen mainScreen].applicationFrame.size.height
#define ScreenRectWidth [UIScreen mainScreen].applicationFrame.size.width


@interface SearchResultViewController ()<UITableViewDataSource,UITableViewDelegate>

@property (weak, nonatomic) IBOutlet UITableView *newsTableView;

@property (nonatomic,strong)NSMutableArray *listNews;

@property (nonatomic,strong)NSURLSessionDataTask *requestHandle;
@property (nonatomic,assign)NSInteger currentPageIndex;

@end

@implementation SearchResultViewController

- (IBAction)back:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
    [self dismissViewControllerAnimated:YES completion:nil];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    __weak typeof(self) weak_self = self;
    self.newsTableView.delegate = self;
    self.newsTableView.dataSource = self;
    self.newsTableView.tableFooterView = [UIView new];
    self.newsTableView.backgroundColor = [[UIColor alloc] initWithRed:0.9 green:0.9 blue:0.9 alpha:1];
    self.newsTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [self.newsTableView registerNib:[UINib nibWithNibName:@"NewsCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"NewsCell"];
    [self.newsTableView registerNib:[UINib nibWithNibName:@"NewsImageCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"NewsImageCell"];
    
    self.newsTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weak_self refreshData];
    }];
    
    self.newsTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [weak_self loadMore];
    }];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.1f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [weak_self.newsTableView.mj_header beginRefreshing];
    });
}

- (void)refreshData
{
    self.currentPageIndex = 1;
    if (self.requestHandle) {
        [self.requestHandle cancel];
        self.requestHandle = nil;
    }
    
    [self.newsTableView.mj_footer resetNoMoreData];
    
    __weak typeof(self) weak_self = self;
        [ServiceNews doSearchNewsList:self.keyWord
                            pageindex:self.currentPageIndex
                             pagesize:DEFAULT_PAGE_SIZE
                              success:^(id responseObject, NSString *message) {
        
        [weak_self.newsTableView.mj_header endRefreshing];
        NSArray *listNews_ = (NSArray *)responseObject;
        weak_self.listNews = [NSMutableArray array];
        if (listNews_) {
            [weak_self.listNews addObjectsFromArray:listNews_];
        }
        
        [weak_self.newsTableView reloadData];
        
    } failure:^(NSString *message) {
        [weak_self.newsTableView.mj_header endRefreshing];
    }];
}

- (void)loadMore
{
    self.currentPageIndex ++;
    if (self.requestHandle) {
        [self.requestHandle cancel];
        self.requestHandle = nil;
    }
    
    __weak typeof(self) weak_self = self;
    [ServiceNews doSearchNewsList:self.keyWord
                        pageindex:self.currentPageIndex
                         pagesize:DEFAULT_PAGE_SIZE
                          success:^(id responseObject, NSString *message) {
        
        [weak_self.newsTableView.mj_footer endRefreshing];
        NSArray *listNews_ = (NSArray *)responseObject;
        if (listNews_) {
            [weak_self.listNews addObjectsFromArray:listNews_];
        }
        
        [weak_self.newsTableView reloadData];
        [weak_self.newsTableView.mj_footer endRefreshing];

    } failure:^(NSString *message) {
        [weak_self.newsTableView.mj_footer endRefreshing];
        [weak_self.newsTableView.mj_footer endRefreshingWithNoMoreData];
    }];
}

- (void)jumpToNewsDetail:(M_News *)news_
{
    [ServiceNews doSendRead:news_.f_id
                    success:^(id responseObject, NSString *message)
     {}
                    failure:^(NSString *message)
     {}];
    
    //3种跳转方式
    if ([news_.f_type isEqualToString:@"slide"]) {
        //图集
        NewsAlbumViewController *controller = [NewsAlbumViewController new];
        controller.hidesBottomBarWhenPushed = YES;
        controller.urlString = news_.f_url;
        controller.f_thumbnail = news_.f_thumbnail;
        if ( [[[UIDevice currentDevice]systemVersion] floatValue] >= 8.0) {
            [self showViewController:controller sender:self];
        }else{
            [self.navigationController pushViewController:controller animated:YES];
        }
    }
    else if([news_.f_type isEqualToString:@"doc"]) {
        if ([news_.f_commentsUrl rangeOfString:@"type=forward"].location != NSNotFound) {
            //外链新闻
            NewsWebViewController *controller = [NewsWebViewController new];
            controller.hidesBottomBarWhenPushed = YES;
            controller.urlString = news_.f_commentsUrl;
            controller.imgUrlString = news_.f_thumbnail;
            controller.titleString = news_.f_title;
            if ([news_.f_commentsUrl rangeOfString:@"share=true"].location != NSNotFound)
            {
                controller.hasShare = YES;
            }
            [self.navigationController pushViewController:controller animated:YES];
        }
        else if ([news_.f_commentsUrl rangeOfString:@"type=adv"].location != NSNotFound) {
            //广告
            NewsWebViewController *controller = [NewsWebViewController new];
            controller.hidesBottomBarWhenPushed = YES;
            controller.urlString = news_.f_commentsUrl;
            controller.imgUrlString = news_.f_thumbnail;
            controller.titleString = news_.f_title;
            if ([news_.f_commentsUrl rangeOfString:@"share=true"].location != NSNotFound)
            {
                controller.hasShare = YES;
            }
            [self.navigationController pushViewController:controller animated:YES];
        }
        else if ([news_.f_commentsUrl rangeOfString:@"type=zt"].location != NSNotFound) {
            //专题链接形式
            NewsWebViewController *controller = [NewsWebViewController new];
            controller.hidesBottomBarWhenPushed = YES;
            controller.urlString = news_.f_commentsUrl;
            controller.imgUrlString = news_.f_thumbnail;
            controller.titleString = news_.f_title;
            if ([news_.f_commentsUrl rangeOfString:@"share=true"].location != NSNotFound)
            {
                controller.hasShare = YES;
            }
            [self.navigationController pushViewController:controller animated:YES];
        }
        else if ([news_.f_commentsUrl rangeOfString:@"specialid="].location != NSNotFound) {
            //专题
            SpecialNewsListViewController *controller = [SpecialNewsListViewController new];
            controller.hidesBottomBarWhenPushed = YES;
            controller.subURL = news_.f_commentsUrl;
            [self.navigationController pushViewController:controller animated:YES];
        }
        else {
            //普通新闻详情，需要请求详情，拼接HTML
            NewsDetailViewController *controller = [NewsDetailViewController new];
            controller.hidesBottomBarWhenPushed = YES;
            controller.urlString = [NSString stringWithFormat:@"%@&aid=%@",URL_SUB_GET_NEWS_DETAIL,news_.f_id];
            controller.f_thumbnail = news_.f_thumbnail;
            if ( [[[UIDevice currentDevice]systemVersion] floatValue] >= 8.0) {
                [self showViewController:controller sender:self];
            }else{
                [self.navigationController pushViewController:controller animated:YES];
            }
        }
    }
    else {
        //待定
    }
}

#pragma mark tableViewDatasouce Delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.listNews count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    M_News *news = [self.listNews objectAtIndex:indexPath.row];
    
    if ([news.f_commentsUrl rangeOfString:@"type=adv"].location != NSNotFound) {
        //3张图片的新闻
        NewsAdvCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NewsAdvCell"];
        cell.newsData = news;
        return cell;
    }
    
    if ([news.f_type isEqualToString:@"doc"]) {
        //普通新闻，一张图，标题
        NewsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NewsCell"];
        cell.newsData = news;
        
        cell.zanIcon.hidden = YES;
        cell.zanLable.hidden = YES;
        cell.viewIcon.hidden = YES;
        cell.labelViewCount.hidden = YES;

        return cell;
    }
    else if([news.f_type isEqualToString:@"slide"]) {
        //3张图片的新闻
        NewsImageCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NewsImageCell"];
        cell.newsData = news;
        
        cell.zanIcon.hidden = YES;
        cell.lableZan.hidden = YES;
        cell.viewIcon.hidden = YES;
        cell.labelViewCount.hidden = YES;

        return cell;
    }
    else {
        //其他，待定
        NewsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NewsCell"];
        cell.newsData = news;
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    M_News *news = [self.listNews objectAtIndex:indexPath.row];
    
    if ([news.f_type isEqualToString:@"doc"]) {
        //普通新闻，一张图，标题
        return 100.0f;
    }
    else if([news.f_type isEqualToString:@"slide"]) {
        //3张图片的新闻
        return 155.0f;
    }
    else {
        //其他，待定
        return 0;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    M_News *news_ = [self.listNews objectAtIndex:indexPath.row];
    [self jumpToNewsDetail:news_];
}

@end
